﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AllInOne.PrintUtils;
using System.Windows.Forms;
using mshtml;
using System.Threading;
using System.Net;
using System.IO;
using System.Runtime.InteropServices;

namespace AllInOne.FeeUtils
{

    [System.Runtime.InteropServices.ComVisible(true)]
    class FeeUtil
    {
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetGetCookie(string lpszUrlName, string lbszCookieName, StringBuilder lpszCookieData, ref int lpdwSize);

        [DllImport("kernel32.dll")]
        public static extern int GetLastError();

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);


        public static string FEE_URL;

        public static string FEE_AREA_CODE;
        public static string FEE_ZTH;
        public static string FEE_USERNAME;
        public static string FEE_PASSWORD;



        private void AddCookie(CookieCollection tempCookieColl, string tempStrCookies, string domain)
        {
            System.Console.WriteLine("============设置Cookies开始===========");
            string[] array = tempStrCookies.Split(new char[]
            {
                ';'
            });
            foreach (string text in array)
            {
                string text2 = string.Empty;
                string text3 = string.Empty;
                Cookie cookie = new Cookie();
                cookie.Expires = DateTime.Now.Add(new TimeSpan(1000, 0, 0));
                string text4 = text.Trim();
                if (!string.IsNullOrEmpty(text4))
                {
                    if (text4.Contains("="))
                    {
                        string[] array3 = text.Split(new char[]
                        {
                            '='
                        });
                        if (array3.Length > 1)
                        {
                            text2 = array3[0].Trim();
                            text3 = array3[1].Trim();
                        }
                        else if (array3.Length == 1)
                        {

                            text2 = array3[0].Trim();
                            text3 = string.Empty;

                        }
                    }

                    else
                    {
                        text2 = text4;
                        text3 = string.Empty;
                    }
                    cookie.Name = text2;
                    cookie.Value = text3;
                    cookie.Path = "/";
                    cookie.Domain = domain;
                    tempCookieColl.Add(cookie);
                    FeeUtil.InternetSetCookie(string.Format("{0}/trffweb/ywsl.do?method=frd_reg", BASE_URL), text2, text3.ToString() + ";expires = Sun,18-Jul-2021 00:00:00 GMT");
                    System.Console.WriteLine("============设置Cookies结束===========");
                }
            }
        }


        public static string BASE_URL = "http://10.231.49.31:9080/fee";

        private MyWebBrowser webBrowser = new MyWebBrowser();

        private string checkUrl = "";

        private string respData = "";

        private bool nagigated = false;

        private HtmlDocument htmlDocument;

        private HtmlDocument webHtmlDocument;

        private Action<string, string> urledHandler;


        private CookieContainer cookies = null;

        private string strCookies = string.Empty;

        private CookieCollection cookieColl = null;

        private string alertMsg = string.Empty;

        private string parseDom = string.Empty;

        public FeeUtil()
        {
            this.webBrowser.WBDocHostShowUIShowMessage += this.webBrowser_WBDocHostShowUIShowMessage;
            this.webBrowser.Navigated += this.webBrowser_Navigated;
            this.webBrowser.Navigating += this.webBrowser_Navigating;
            this.webBrowser.DocumentCompleted += this.webBrowser_DocumentCompleted;
            this.webBrowser.ScriptErrorsSuppressed = true;
            this.webBrowser.Visible = true;
            //this.webBrowser.ObjectForScripting = this;

        }


        public void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            this.nagigated = false;
            System.Console.WriteLine("正在导航..." + e.Url);
        }


        public void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            try
            {
                IHTMLWindow2 ihtmlwindow = this.webBrowser.Document.Window.DomWindow as IHTMLWindow2;
                string code = "window.alert = function(msg){window.external.myAlert(msg);};";
                ihtmlwindow.execScript(code, "JScript");
            }
            catch (Exception value)
            {
                System.Console.Write(value);
            }
        }

        public void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string absoluteUri = e.Url.AbsoluteUri;

            System.Console.WriteLine("成功导航到指定Url  ----> " + absoluteUri);
            if (absoluteUri.Equals(this.checkUrl))
            {
                this.webHtmlDocument = this.webBrowser.Document;
                this.respData = this.webHtmlDocument.Body.OuterHtml;
                this.nagigated = true;
                System.Console.WriteLine("成功导航到指定Url");
                if (this.urledHandler != null)
                {
                    this.urledHandler(absoluteUri, this.respData);
                }
            }
        }

        public void webBrowser_WBDocHostShowUIShowMessage(object sender, ExtendedBrowserMessageEventArgs e)
        {
            e.Cancel = true;
            this.alertMsg = e.Text;
            System.Console.WriteLine("捕获Alert弹框消息：" + this.alertMsg);
        }


        private WebBrowser Execute(WebBrowser browser, string url)
        {
            bool loadFinished = false;
            int num = 10;
            try
            {
                browser.DocumentCompleted += delegate (object a, WebBrowserDocumentCompletedEventArgs b)
                {
                    System.Console.WriteLine("已导航到的Url->" + b.Url);
                    loadFinished = true;
                };
                System.Console.WriteLine("即将要导航的Url->" + url);
                browser.Navigate(new Uri(url), false);
                while (!loadFinished && num > 0)
                {
                    Thread.Sleep(200);
                    System.Console.WriteLine("第[" + (10 - num) + "]尝试等待");
                    Application.DoEvents();
                    num--;
                }
                string title = browser.Document.Title;
                if ("导航已取消" == title)
                {
                    throw new Exception("无法连接远程服务");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return browser;
        }


        public void Login(Action<bool> setLoginResult)
        {
            this.Login(FEE_AREA_CODE, FEE_ZTH, FEE_USERNAME, FEE_PASSWORD, setLoginResult);
        }

        public void Login(string departId, string zth, string userId, string pwd, Action<bool> setLoginResult)
        {

            this.checkUrl = BASE_URL + "/feeLogin.do";
            this.urledHandler = new Action<string, string>(delegate (string url, string data)
            {
                //Console.WriteLine(data);
                HtmlDocument document = this.webBrowser.Document.Window.Document;
                bool loadedFlag = false;
                foreach (HtmlElement selectElement in document.GetElementsByTagName("select"))
                {
                    if (selectElement.Name == "userDepartment")
                    {
                        selectElement.SetAttribute("value", departId);
                        loadedFlag = true;
                    }
                }

                foreach (HtmlElement selectElement in document.GetElementsByTagName("select"))
                {
                    if (selectElement.Name == "userAccountId")
                    {
                        selectElement.SetAttribute("value", zth);
                        loadedFlag = true;
                    }
                }
                foreach (HtmlElement inputElement in document.GetElementsByTagName("input"))
                {
                    if (inputElement.Name == "userId")
                    {
                        inputElement.SetAttribute("value", userId);
                    }
                    else if (inputElement.Name == "userPassword")
                    {
                        inputElement.SetAttribute("value", pwd);
                    }
                }
                if (!loadedFlag)
                {
                    setLoginResult(false);
                    return;
                }


                this.checkUrl = BASE_URL + "/feeLogin.do";
                this.urledHandler = new Action<string, string>(delegate (string newUrl, string newData)
                {
                    //Console.WriteLine(newData);
                    if (this.webBrowser.Document.Window.Document.Body.OuterHtml.IndexOf("homeDispatch.do") > -1)
                    {

                        setLoginResult(true);

                    }
                    else
                    {
                        setLoginResult(false);
                    }
                });
                document.InvokeScript("func_login");
            });

            this.webBrowser.Navigate(new Uri(BASE_URL + "/index.jsp"), false);


        }

        public void GetQrCodeUrl(string lsh, Action<string> setQrCodeJpgUrl)
        {

            try
            {
                this.checkUrl = null;
                string qrcodeUrl = string.Format("{0}/drvFlogPosTc.do?type=lshmatic&lshcx={1}", BASE_URL, lsh);
                this.checkUrl = qrcodeUrl;
                this.urledHandler = new Action<string, string>(delegate (string url, string data) {
                    //Console.WriteLine(data);

                    int startIndex = data.IndexOf(@"jsp/ewm/");
                    if (startIndex > -1)
                    {
                        string qrCodeJpgUrl = BASE_URL + "/" + data.Substring(startIndex, 31);
                        setQrCodeJpgUrl(qrCodeJpgUrl);
                    }
                    else
                    {
                        setQrCodeJpgUrl(null);
                    }
                });

                this.webBrowser.Navigate(new Uri(checkUrl), false);
            }
            catch (Exception ex)
            {

            }

        }


        public void CheckPayState(string jym, Action<bool> setPayState)
        {

            string payStateUrl = string.Format("{0}/DrvFlogAjaxAction.do?type=getpay&orderid={1}", BASE_URL, jym);
            this.checkUrl = payStateUrl;
            this.urledHandler = new Action<string, string>(delegate (string url, string data) {

                var fontElements = this.webBrowser.Document.Window.Document.GetElementsByTagName("font");
                if (fontElements.Count > 0)
                {
                    Console.WriteLine("交费结果:" + fontElements[0].InnerText);
                    if (fontElements[0].InnerText == "1")
                    {
                        setPayState(true);
                    }
                    else
                    {
                        setPayState(false);
                    }
                }
                else
                {
                    setPayState(false);
                }

                //Console.WriteLine(data);
            });
            this.webBrowser.Navigate(new Uri(checkUrl), false);

        }
    }
}
